import axios from 'axios';

const API_KEY = process.env.VUE_APP_DIFY_API_KEY || "dataset-R9DDuqVdlAViKb2mIx06ew3v";

const dify = axios.create({
  baseURL: `/dify/v1`,
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json'
  }
});

// 知识库文档接口
export const getDocuments = (datasetId: string, params?: any) => 
  dify.get(`/datasets/${datasetId}/documents`, { params });


export const deleteDocument = (datasetId: string, documentId: string) =>
  dify.delete(`/datasets/${datasetId}/documents/${documentId}`);

export const getDocumentFile = (datasetId: string, documentId: string) =>
  dify.get(`/datasets/${datasetId}/documents/${documentId}/upload-file`);


export const createDocumentByFile = (
    datasetId: string,
    data: {
      file: File
      data: string // JSON string
      retrieval_model?: string
      embedding_model?: string
      embedding_model_provider?: string
    }
  ) => {
    const formData = new FormData()
    
    // 添加文件
    formData.append('file', data.file)

    // 添加结构化参数
    formData.append('data', JSON.stringify(data.data))
  
    // 添加其他可选参数
    if (data.retrieval_model) {
      formData.append('retrieval_model', data.retrieval_model)
    }
    if (data.embedding_model) {
      formData.append('embedding_model', data.embedding_model)
    }
    if (data.embedding_model_provider) {
      formData.append('embedding_model_provider', data.embedding_model_provider)
    }
  
    return dify.post(`/datasets/${datasetId}/document/create-by-file`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
         'Authorization': `Bearer ${API_KEY}`,
      }
    })
  }
  export const createDocumentWithProcessRule = (
    datasetId: string,
    params: {
      file: File
      processRule: {
        indexing_technique: 'high_quality' | 'economy'
        mode: 'automatic' | 'custom'
        preProcessingRules: Array<{ id: string; enabled: boolean }>
        segmentation: {
          separator: string
          max_tokens: number
          chunk_overlap?: number
        }
        doc_form?: 'text_model' | 'hierarchical_model' | 'qa_model' // 新增字段
        doc_language?: string // 新增字段（QA 模式必填）
      }
    }
  ) => {
    const formData = new FormData()
  
    // 构建结构化参数（补充必填字段）
    const dataPayload: Record<string, any> = {
      indexing_technique: params.processRule.indexing_technique,
      process_rule: {
        mode: params.processRule.mode,
        rules: params.processRule.mode === 'custom' ? {
          pre_processing_rules: params.processRule.preProcessingRules,
          segmentation: params.processRule.segmentation
        } : undefined
      }
    }
  
    // 补充文档形式和语言
    if (params.processRule.doc_form) {
      dataPayload.doc_form = params.processRule.doc_form
    }
    if (params.processRule.doc_language) {
      dataPayload.doc_language = params.processRule.doc_language
    }
  
    // 序列化参数
    formData.append('data', JSON.stringify(dataPayload))
  
    // 添加文件
    formData.append('file', params.file, params.file.name)
    console.log(formData)
    return dify.post(`/datasets/${datasetId}/document/create-by-file`, formData)
}

// 获取批量文档处理状态
export const getBatchIndexingStatus = (
  datasetId: string, 
  batch: string
) => {
  return dify.get<{
    data: Array<{
      id: string
      indexing_status: string
      completed_segments: number
      total_segments: number
      error?: string
      // 其他字段根据需求扩展
    }>
  }>(`/datasets/${datasetId}/documents/${batch}/indexing-status`)
}

// 获取单个文档状态（基于批次接口）
export const getDocumentStatus = async (
  datasetId: string,
  documentId: string,
  batch: string
) => {
  const res = await getBatchIndexingStatus(datasetId, batch)

  return res.data.data.find(doc => doc.id === documentId) // 适配数组结构
}